//
//  XYJXHViewController.m
//  徙游记-01
//
//  Created by hcios on 2017/7/14.
//  Copyright © 2017年 鹿林. All rights reserved.
//

#import "XYJXHViewController.h"
#import "SDWebImageManager.h"
#import "XLPhotoBrowser.h"

#import "UserLikeModel.h"
#import "WaterFlowCell.h"
#import "WaterfallLayout.h"
#import "UIImageView+WebCache.h"
#import "UIView+XLExtension.h"

@interface XYJXHViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,WaterfallLayoutDelegate,WaterFlowCellDelegate,XLPhotoBrowserDelegate,XLPhotoBrowserDatasource>{
    //数据源
    NSMutableArray *_dataArray;
    NSMutableArray *_dataUrlArray;
    NSMutableArray *_dataImageViewArray;
    
    NSInteger page;
    
    NSIndexPath *indexpath;
}

@property (nonatomic,strong) UICollectionView *cardView;


@end

static NSString *const CollectionViewCellIdentifier = @"cellID";

@implementation XYJXHViewController

-(instancetype)init{
    if (self = [super init]) {
        _dataArray = [[NSMutableArray alloc] init];
        _dataUrlArray = [[NSMutableArray alloc] init];
        _dataImageViewArray = [[NSMutableArray alloc] init];
        indexpath = [[NSIndexPath alloc] init];
        page = 1;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self layoutCollectionView];
    
    [self.cardView.mj_header beginRefreshing];
    
    self.view.backgroundColor = [UIColor yellowColor];
    
}


#pragma mark - refresh
-(void)refreshGetData:(BOOL)isRefresh{
    
    isRefresh?page = 1:page++;
    NSString * urlString = @"http://chanyouji.com/api/users/likes/705176.json";
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObject:@(page) forKey:@"page"];
    /*网络请求*/
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    [manger GET:urlString parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dict = responseObject;
        if (isRefresh) {
            //清空数组
            [_dataUrlArray removeAllObjects];
            [_dataImageViewArray removeAllObjects];
            [_dataArray removeAllObjects];
            self.cardView.mj_footer.state = MJRefreshStateIdle;
        }
        if ([dict count]>0) {
            //清空数组
            
            for (NSDictionary * dict in responseObject) {
                //取值
                UserLikeModel * model = [[UserLikeModel alloc]initWithDict:dict];
                [_dataArray addObject:model];
                [_dataUrlArray addObject:model.photo_url];
            }
        }
        if (_dataArray.count < 10) {
            [self.cardView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.cardView reloadData];
        if (!isRefresh && [dict count] == 0) {
            [self.cardView.mj_footer endRefreshingWithNoMoreData];
        }else [self endRefresh];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络请求失败");
    }];
}

-(void)endRefresh{
    
    if (page == 1) {
        [self.cardView.mj_header endRefreshing];
    }else [self.cardView.mj_footer endRefreshing];
}

#pragma mark - 初始化collectionView
- (void)layoutCollectionView{
    
    //初始化layout
    WaterfallLayout * layout = [[WaterfallLayout alloc] init];
    //滑动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //宽度
    CGFloat w = (SCREEN_WIDTH - 30) / 2;
    //设置每个cell的大小
    layout.itemSize = CGSizeMake(w, w);
    //每个cell之间的距离
    layout.insertItemSpacing = 10.0f;
    //列数
    layout.numberOfColumn = 2;
    //内边距
    layout.sectionInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.delegate = self;
    self.cardView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 274) collectionViewLayout:layout];
    self.cardView.delegate = self;
    self.cardView.dataSource = self;
    self.cardView.showsVerticalScrollIndicator = NO;
    //注册cell
    [self.cardView registerClass:[WaterFlowCell class] forCellWithReuseIdentifier:@"cellID"];
    self.cardView.backgroundColor = [UIColor colorWithRed:214.0 / 255.0 green:226.0 / 255.0 blue:238.0 / 255.0 alpha:1.0];
    //刷新
    __weak typeof(self) weakSelf = self;
    //取消上啦刷新（避免bug）
    self.cardView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf refreshGetData:YES];
    }];
    self.cardView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf refreshGetData:NO];
    }];
    [self.view addSubview:self.cardView];
}

#pragma mark - collectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _dataArray.count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    WaterFlowCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CollectionViewCellIdentifier forIndexPath:indexPath];
    //加载本地数据
    //[cell modelWithDict:_dataArr[indexPath.row]];
    //网络加载
    UserLikeModel * model = _dataArray[indexPath.row];
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:model.photo_url] placeholderImage:[UIImage imageNamed:@"zhanWeiTu"]];
    [_dataImageViewArray addObject:cell.imgView];
    cell.delegate = self;
    return cell;
}

#pragma mark - collectionViewDelegate
//设置边距
- (UIEdgeInsets) collectionView:(UICollectionView *)collectionView
                         layout:(UICollectionViewLayout *)collectionViewLayout
         insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10.0f, 10.0f, 0.0f, 10.0f);
}

// 计算高度
- (CGFloat)heightForItemIndexPath:(NSIndexPath *)indexPath{
    UserLikeModel * m = _dataArray[indexPath.item];
    CGFloat w = (SCREEN_WIDTH - 30) / 2;
    CGFloat h = (w * [m.image_height integerValue]) / [m.image_Width integerValue];
    return h;
}


//图片点击方法
-(void)click:(UITapGestureRecognizer *)tap{
    NSLog(@"点击图片");
    //获取点击图片的indexRow
    UIImageView *img = (UIImageView *)tap.view;
    CGPoint point = img.center;
    point = [self.cardView convertPoint:point fromView:img.superview];
    indexpath = [self.cardView indexPathForItemAtPoint:point];
    
    //快速创建并进入浏览模式
    XLPhotoBrowser *browser = [XLPhotoBrowser showPhotoBrowserWithCurrentImageIndex:indexpath.row imageCount:_dataUrlArray.count datasource:self];
    //隐藏小圆点
    browser.showPageControl = NO;
    browser.pageControlStyle = XLPhotoBrowserPageControlStyleNone;
    // 设置长按手势弹出的地步ActionSheet数据,不实现此方法则没有长按手势
    [browser setActionSheetWithTitle:@"" delegate:self cancelButtonTitle:@"取消" deleteButtonTitle:nil otherButtonTitles:@"保存图片",@"收藏",nil];
    
    // 自定义一些属性
    browser.pageDotColor = [UIColor purpleColor]; ///< 此属性针对动画样式的pagecontrol无效
    browser.currentPageDotColor = [UIColor greenColor];
    //browser.pageControlStyle = XLPhotoBrowserPageControlStyleAnimated;///< 修改底部pagecontrol的样式为系统样式,默认是弹性动画的样式
}


#pragma mark    -   XLPhotoBrowserDatasource

/**
 *  返回这个位置的占位图片 , 也可以是原图(如果不实现此方法,会默认使用placeholderImage)
 *
 *  @param browser 浏览器
 *  @param index   位置索引
 *
 *  @return 占位图片
 */
- (UIImage *)photoBrowser:(XLPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    return nil;
}

/**
 *  返回指定位置图片的UIImageView,用于做图片浏览器弹出放大和消失回缩动画等
 *  如果没有实现这个方法,没有回缩动画,如果传过来的view不正确,可能会影响回缩动画效果
 *
 *  @param browser 浏览器
 *  @param index   位置索引
 *
 *  @return 展示图片的容器视图,如UIImageView等
 */
- (UIView *)photoBrowser:(XLPhotoBrowser *)browser sourceImageViewForIndex:(NSInteger)index
{
    return _dataImageViewArray[indexpath.row];
}

/**
 *  返回指定位置的高清图片URL
 *
 *  @param browser 浏览器
 *  @param index   位置索引
 *
 *  @return 返回高清大图索引
 */
- (NSURL *)photoBrowser:(XLPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
    return [NSURL URLWithString:_dataUrlArray[index]];
}


#pragma mark    -   XLPhotoBrowserDelegate

- (void)photoBrowser:(XLPhotoBrowser *)browser clickActionSheetIndex:(NSInteger)actionSheetindex currentImageIndex:(NSInteger)currentImageIndex
{
    switch (actionSheetindex) {
            
        case 0: // 保存
        {
            NSLog(@"点击了actionSheet索引是:%zd , 当前展示的图片索引是:%zd",actionSheetindex,currentImageIndex);
            [browser saveCurrentShowImage];
        }
            break;
        case 1: // 收藏
        {
            NSLog(@"点击了actionSheet索引是:%zd , 当前展示的图片索引是:%zd",actionSheetindex,currentImageIndex);
            NSLog(@"点击收藏");
        }
            break;
        default:
        {
            NSLog(@"点击了actionSheet索引是:%zd , 当前展示的图片索引是:%zd",actionSheetindex,currentImageIndex);
        }
            break;
    }
}

@end

